package cn.learn.validate.sms;

import cn.learn.validate.impl.AbstractValidateCodeProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 短信的处理器
 *
 * @author huangyezhan
 * @date 2020年02月21日12:54
 */
@Component
public class SmsValidateCodeProcessor extends AbstractValidateCodeProcessor<SmsCode> {

    /**
     * 短信验证码发送器
     */
    @Autowired
    private SmsCodeSender smsCodeSender;

    /**
     * 短信发送
     *
     * @param response     响应
     * @param validateCode 验证码的相关消息
     */
    @Override
    protected void send(HttpServletResponse response, SmsCode validateCode) {
        String phoneNumber = validateCode.getPhoneNumber();
        smsCodeSender.send(phoneNumber, validateCode.getCode());
    }

    @Override
    protected void save(HttpServletRequest request, SmsCode validateCode) {
        String  sessionKey  = this.getSessionKey(request);
        SmsCode sessionCode = (SmsCode) request.getSession().getAttribute(sessionKey);
        if (sessionCode == null) {
            super.save(request, validateCode);
        } else {
            sessionCode.setCode(validateCode.getCode());
            sessionCode.setExpireTime(validateCode.getExpireTime());
            sessionCode.setRefreshNum(validateCode.getRefreshNum() + 1);
            sessionCode.setTotalValidations(validateCode.getTotalValidations());
            sessionCode.setValidateNum(validateCode.getValidateNum());

            sessionCode.setIntervalTime(validateCode.getIntervalTime());
            sessionCode.setPhoneNumber(validateCode.getPhoneNumber());
            sessionCode.setMsg(validateCode.getMsg());
            sessionCode.setSendTotalNum(validateCode.getSendTotalNum());
        }


    }
}
